package com.thinkTank.oa.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.thinkTank.oa.common.Constant;
import com.thinkTank.oa.configuration.Log;
import com.thinkTank.oa.entity.Dictiontry;
import com.thinkTank.oa.entity.Role;
import com.thinkTank.oa.entity.User;
import com.thinkTank.oa.entity.UserGroup;
import com.thinkTank.oa.lucene.IsolrOperation;
import com.thinkTank.oa.lucene.LucenePerson;
import com.thinkTank.oa.lucene.Pagination;
import com.thinkTank.oa.lucene.SolrOperation;
import com.thinkTank.oa.service.RoleService;
import com.thinkTank.oa.service.UserGroupService;
import com.thinkTank.oa.util.MD5Util;
import com.thinkTank.oa.util.StrUtil;

/***
 * 用户类
 * @author dq
 *
 */
@RequestMapping("/user")
@Controller
public class UserController extends BaseController {
	
	private final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	

	
	@Autowired
	private RoleService roleService;
	@Resource
	private UserGroupService userGroupService;
	
	private void addAttrModel(Model model) {
		List<Dictiontry> userGroupDicList = getDicList(Constant.DICTIONTRY_USERGROUP);
		model.addAttribute("userGroupDicList", userGroupDicList);
	}
	
	/***
	 * 显示用户列表
	 * @author dq
	 * @date 2018-08-09
	 * @param pageNo 当前第几页
	 * @return
	 */
	@Log("查看用户列表")
	@ RequestMapping(value= "showUserList")
	public String showUserList(Integer pageNo,HttpServletRequest request,String searchKeyword, Model model){
		try{
			addAttrModel(model);
			if(null==pageNo){
				pageNo=1;
			}
			 PageHelper.startPage(pageNo, DEFAULT_COUNT);
			 User user = new User();
			 /**
			  * 根据姓名或者邮箱检索
			  */
			 if(searchKeyword!=null&&!"".endsWith(searchKeyword)){
				 if(searchKeyword.indexOf("@")>0){
					 user.setUserName(searchKeyword);
				 }else{
					 user.setFullName(searchKeyword);
				 }
			 }
			 List<User> list = userService.queryAll(user);//只对第一个查询分页
			 PageInfo<User> pageInfo = new PageInfo<User>(list);
			 request.setAttribute("pageInfo", pageInfo);
			 request.setAttribute("searchKeyword", searchKeyword);
			 
			 List<String> userIdList = pageInfo.getList().stream().map(User::getPid).collect(Collectors.toList());
			 UserGroup userGroup = new UserGroup().setUserIdList(userIdList);
			 List<UserGroup> userGroupList = queryUserGroup(userGroup);
			 Map<String, String> useridAndGroupMap = userGroupList.stream().collect(Collectors.groupingBy(UserGroup::getUserId, 
					 Collectors.mapping(ug -> ug.getGroupName() + "-" + ug.getPositionName(), Collectors.joining(","))));
			 model.addAttribute("useridAndGroupMap", useridAndGroupMap);
		}catch(Exception e){
			logger.error(e.getMessage());
		}
		
		return "showuserlist";
	}
	
	/***
	 * 显示用户列表
	 * @author dq
	 * @date 2018-08-09
	 * @param pageNo 当前第几页
	 * @return
	 */
	@Log("查看用户列表")
	@ RequestMapping(value= "showUserListTest")
	public String showUserListTest(Integer pageNo,HttpServletRequest request,String searchKeyword){
		try{
			if(null==pageNo){
				pageNo=1;
			}

			IsolrOperation<LucenePerson > solr=new   SolrOperation<LucenePerson>();
			Pagination pa = solr.queryList(pageNo, 10, 7, "630699d6f9324f4491c5091b8bf2fb21", null, null, "化学化工");
			
			 request.setAttribute("pageInfo", pa);
			 request.setAttribute("searchKeyword", searchKeyword);
		}catch(Exception e){
			logger.error(e.getMessage());
		}
		
		return "showuserlist1";
	}
	
	
	/***
	 * 显示添加用户页面
	 * @author dq
	 * @date 2018-08-09
	 * @return
	 */
	@ RequestMapping(value= "showAddUser")
	public String showAddUser(Model model){
		try{
			if(!model.containsAttribute("user")){
				model.addAttribute("user", new User());
			}
			//查询所有的角色用于前台显示
			List<Role> role = roleService.queryAll(new Role());
			model.addAttribute("roles", role);
		}catch(Exception e ){
			logger.error(e.getMessage());
		}
		
		return "showadduser";
		
	}
	/***
	 * 添加用户
	 * @author dq
	 * @date 2018-08-09
	 * @return
	 */
	@ RequestMapping(value= "addUser")
	public String addUser(@Valid User user, BindingResult result,Model model){
		try{
			/**
			 * 验证
			 */
			User checkUser = userService.getUserByUsername(user.getUserName());
			if(checkUser!=null){
				result.rejectValue("userName","userNameFormat", "该用户名已经存在");
			}
			//person.getEmail1().matches(ConfigKeys.REGEX_EMAIL)
			if(!user.getUserName().matches(Constant.REGEX_EMAIL)){
				result.rejectValue("userName","userNameFormat", "改用户名无效,必须是邮箱");
			}
			if(user.getUserPwd()==null||"".equals(user.getUserPwd())){
				result.rejectValue("userPwd","userPwdFormat", "用户密码不能为空");
			}
			
			if (result.hasErrors()) {
				model.addAttribute("user", user);
				return showAddUser(model);
			}
			user.setMd5(MD5Util.MD5(user.getUserPwd()));
			user.setAddTime(StrUtil.getCurrentDateTime());
			user.setDisable(1);
			user.setPid(StrUtil.getUUID32());
			/**
			 * 添加用户
			 */
			userService.addUserAndRole(user);
		}catch(Exception e){
			logger.error(e.getMessage());
		}
		
		return "redirect:/user/showUserList";
		
	}
	
	/***
	 * 显示修改用户页面
	 * @author dq
	 * @param 页面传过来的 用户Id
	 * @date 2018-08-09
	 * @return
	 */
	@ RequestMapping(value= "showUpdateUser")
	public String showUpdateUser(String userId,Model model){
		
			User user = userService.findUserById(userId);
			if(!model.containsAttribute("user")){
				model.addAttribute("user", user);
			}
			List<Role> role = roleService.queryAll(new Role());
			model.addAttribute("roles", role);
			List<Role> roles = user.getRoles();
			String strRole="";
			for(Role s :roles){
				strRole+=s.getName()+",";
			}
			model.addAttribute("userRoles", strRole);
		
		return "showupdateuser";
		
	}
	
	/**
	 * 修改用户
	 * @author dq
	 * @date 2018-08-09
	 * @return
	 */
	@ RequestMapping(value= "updateUser")
	public String updateUser(@Valid User user,BindingResult result,Model model){
		try{
			/**
			 * 验证
			 * 当用户修改了登录名在验证是否重复
			 */
			User u1 = userService.findUserById(user.getPid());
			if(!u1.getUserName().equals(user.getUserName())){
				User checkUser = userService.getUserByUsername(user.getUserName());
				if(checkUser!=null){
					result.rejectValue("userName","userNameFormat", "该用户名已经存在");
				}
			}
			if (result.hasErrors()) {
				model.addAttribute("user", user);//错误信息绑定在user里面
				return showUpdateUser(user.getPid(),model);
			}
			User olderuser = userService.findUserById(user.getPid());
			
			if(null != olderuser){
				if(user.getUserPwd()!=null&&!user.getUserPwd().equals("")){
					olderuser.setMd5(MD5Util.MD5(user.getUserPwd()));
				}
				if(user.getTell()!=null&!user.getTell().equals("")){
					olderuser.setTell(user.getTell());
				}
				if(user.getFullName()!=null&!user.getFullName().equals("")){
					olderuser.setFullName(user.getFullName());
				}
				if (user.getDisable() != null) {
					olderuser.setDisable(user.getDisable());
				}
				olderuser.setRole(user.getRole());
			}
			userService.updateUserAndRole(olderuser);
		}catch(Exception e){
			logger.error(e.getMessage());
		}
		
		return "redirect:/user/showUserList";
		
	}
	
	@RequestMapping("/addToUserGroup")
	@ResponseBody
	public String addToUserGroup(UserGroup userGroup) {
		Integer position = userGroup.getPosition();
		List<UserGroup> list = userGroupService.queryAll(userGroup.setPosition(null));
		if (list == null || list.isEmpty())
			userGroupService.add(userGroup.setPid(StrUtil.getUUID32()).setPosition(position));
		return "success";
	}
	
	@RequestMapping("/queryUserGroup")
	@ResponseBody
	public List<UserGroup> queryUserGroup(UserGroup userGroup) {
		List<UserGroup> list = userGroupService.queryAll(userGroup);
		List<Dictiontry> userGroupDicList = getDicList(Constant.DICTIONTRY_USERGROUP);
		list.forEach(ug -> {
			String groupName = userGroupDicList.stream().filter(dic -> dic.getPid().equals(ug.getGroupNameId())).map(Dictiontry::getWorth).findAny().get();
			ug.setGroupName(groupName).setPositionName(ug.getPosition().equals(UserGroup.GROUP_LEADER) ? "组长" : "组员");
		});
		return list;
	}
	
	@RequestMapping("/removeFromUserGroup")
	@ResponseBody
	public String removeFromUserGroup(String userGroupId) {
		userGroupService.delete(userGroupId);
		return "success";
	}
	
}
